32. Exercise: Sunshine FirebaseJobDispatcher
Syncing on demand is great, but don’t we want to continuously update the data for our users, even when the app isn’t in the foreground? After all, who wants to sit and wait for their weather data anymore? I know I certainly don’t! Now that we’ve learned about FirebaseJobDispatcher, let’s make use of it in Sunshine!
Add the FirebaseJobDispatcher dependency
As with any dependency, we’ll need to add FirebaseJobDispatcher to our project. That’s going to be step one here.
Create our FirebaseJobService
Next, we need to create the Service that FirebaseJobDispatcher runs when it, well, runs our service!
- (1) Let’s create a
jobdispatcher.JobServicecalledSunshineFirebaseJobService. It’s important that we verify that we’ve importedjobdispatcher.JobServicerather than the Android framework’sJobService, because if you do, you’ll definitely have some headaches. Double and triple check that please. - (2) Within your Service, override
onStartJoband call to ourSunshineSyncTask.syncWeathermethod in the background. - (3) Once the
syncWeathermethod finishes, calljobFinished, passing the JobParameters argument fromonStartJobas well as a false value to signify that we don’t have any more work to do. - (4) Now, to clean up any mess that may be caused by the framework cancelling our jobs, override
onStopJob, and stop our background thread that was started inonStartJob. - (5) Then, return
trueto tell the system, “Yes please, we’d like to be rescheduled to finish that work that we were doing when you so rudely interrupted us.”
Declare our newly created Service in the Manifest
Although FirebaseJobDispatcher JobServices have some cool features, they are still one of those main four components of the Android framework that need to be declared in the Manifest. Go ahead and do that now, or your app will crash when FirebaseJobDispatcher attempts to run your service.
Modify SunshineSyncUtils
We created SunshineSyncUtils in the last lesson, and we’ll finish it up here.
- (1) Add constant values to represent how frequently, and with what timeframe, we will perform our weather synchronization. Every three to four hours is a good rule of thumb here.
- (2) While we’re at it, let’s add a tag to identify our sync job. Call it
SUNSHINE_SYNC_TAG. - (3) After that, create the method that builds and dispatchers our Job, and then call that method from the
initializemethod (only if the method hasn’t been previously initialized).
Exercise: Sunshine Background Syncing
SOLUTION:
- Add the FirebaseJobDispatcher Gradle dependency
- Create a SunshineFirebaseJobService that calls syncWeather on a Thread.
- Add the SunshineFirebaseJobService to the manifest
- In SunshineSyncUtils, fill out the scheduleFirebaseJobDispatcherSync and add a call to it in the initialize function